﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using Newtonsoft.Json;
using System.Collections;

namespace CarLeasing.Data
{
    public class LocalStore
    {
        public LocalStore(string folder)
        {
            Folder = folder;
            if (!Directory.Exists(folder))
                Directory.CreateDirectory(folder);
        }

        public FileStore<T> Of<T>()
            where T : IEntity
        {
            if (!Files.ContainsKey(typeof(T)))
                Files.Add(typeof(T), new FileStore<T>(Path.Combine(Folder, typeof(T).FullName)));

            return Files[typeof(T)] as FileStore<T>;
        }

        private Dictionary<Type, object> Files = new Dictionary<Type, object>();
        private readonly string Folder;      
    }

    public class FileStore<T>:IEnumerable<T>
        where T : IEntity
    {
        public FileStore(string bakingFile)
        {
            BakingFile = bakingFile;
            if (!File.Exists(BakingFile))
                File.WriteAllText(BakingFile, JsonConvert.SerializeObject(new T[0]));

            Cache = JsonConvert.DeserializeObject<T[]>(File.ReadAllText(BakingFile)).ToDictionary(x => x.Id, x => x);
        }

        public T Find(Guid id) => Cache[id];

        public void Add(T entity) => Cache.Add(entity.Id, entity);

        public void Remove(Guid id) => Cache.Remove(id);

        public void Save() => File.WriteAllText(BakingFile, JsonConvert.SerializeObject(Cache.Values.ToArray(), Formatting.None));

        public readonly string BakingFile;
        private readonly Dictionary<Guid, T> Cache;

        public IEnumerator<T> GetEnumerator() => Cache.Values.GetEnumerator();

        IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
    }
}
